package com.doubao.wechat.util;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 微信支付AES加解密工具类
 * 用于处理微信支付V3 API的AES-GCM加解密
 */
public class WxPayAesUtil {

    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;
    private final byte[] aesKey;

    /**
     * 构造函数
     *
     * @param key APIv3密钥
     */
    public WxPayAesUtil(String key) {
        if (key.length() != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        this.aesKey = key.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 解密
     *
     * @param associatedData 附加数据包
     * @param nonce         随机串
     * @param ciphertext    密文
     * @return 明文
     * @throws GeneralSecurityException 解密失败异常
     */
    public String decryptToString(String associatedData, String nonce, String ciphertext) throws GeneralSecurityException {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT,
                    nonce.getBytes(StandardCharsets.UTF_8));

            cipher.init(Cipher.DECRYPT_MODE, key, spec);

            if (associatedData != null) {
                cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8));
            }

            byte[] bytes = cipher.doFinal(Base64.decodeBase64(ciphertext));
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 静态解密方法，使用APIv3密钥解密
     *
     * @param associatedData 附加数据包
     * @param nonce         随机串
     * @param ciphertext    密文
     * @param apiV3Key      APIv3密钥
     * @return 明文
     * @throws GeneralSecurityException 解密失败异常
     */
    public static String decryptToString(String associatedData, String nonce, String ciphertext, String apiV3Key)
            throws GeneralSecurityException {
        WxPayAesUtil util = new WxPayAesUtil(apiV3Key);
        return util.decryptToString(associatedData, nonce, ciphertext);
    }
}